package com.xhdd.serv;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xhdd.dto.Elec;
import com.xhdd.dto.Repair;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CronServiceImpl implements CronService {
    @Resource
    ElasticsearchClient esClient;
    String indexName = "cron";
    @Resource
    ObjectMapper mapper;

    @Override
    public void save(List<Elec> effects, List<Elec> steps, List<String> codes, List<Repair> repairs) throws IOException {
        UnitMsg unitMsg = new UnitMsg(
                mapper.writeValueAsString(effects), mapper.writeValueAsString(steps),
                mapper.writeValueAsString(codes), mapper.writeValueAsString(repairs), new Date()
        );

        esClient.index(i -> i.index(indexName).document(unitMsg));
    }

    Map<String, Object> getLatestUnitMsg() throws IOException {
        Map<String, Object> map = new HashMap<>();
        SearchResponse<UnitMsg> updtTime = esClient.search(s -> s.index(indexName)
                .from(1).size(1)
                .sort(so -> so.field(f -> f.field("updtTime")
                        .order(SortOrder.Desc))), UnitMsg.class);
        UnitMsg source = updtTime.hits().hits().get(0).source();
        List<String> codes = mapper.readValue(source.getCodes(), mapper.getTypeFactory().constructCollectionType(List.class, String.class));
        List<Elec> effects = mapper.readValue(source.getEffects(), mapper.getTypeFactory().constructCollectionType(List.class, Elec.class));
        List<Elec> steps = mapper.readValue(source.getSteps(), mapper.getTypeFactory().constructCollectionType(List.class, Elec.class));
        List<Repair> repairs = mapper.readValue(source.getRepairs(), mapper.getTypeFactory().constructCollectionType(List.class, Repair.class));

        /*获取空间碰撞的数据*/
        map.put("effect-node", effects);
        map.put("steps", steps);
        map.put("repairs", repairs);
        map.put("effect-others", effects);
        return map;
    }

}
